package org.pp.controller;


import cn.hutool.core.util.IdUtil;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.pp.config.WechatPayConfig;
import org.pp.core.Result;
import org.pp.miniapp.dto.RequestPay;
import org.pp.service.IPpPayService;
import org.pp.vo.MiniappPrepayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/pay")
@Slf4j
public class PpPayController {

    @Autowired
    RSAAutoCertificateConfig certificateConfig;

    @Autowired
    WechatPayConfig config;

    @Autowired
    IPpPayService payService;

    @GetMapping("/test")
    @Operation(summary = "测试支付 生成支付二维码支付")
    public Result<Void> prepayTest(){
        NativePayService service = new NativePayService.Builder()
                .config(certificateConfig).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(100);
        request.setAmount(amount);
        request.setAppid(config.getAppid());
        request.setMchid(config.getMerchantId());
        request.setDescription("测试支付");
        request.setNotifyUrl(config.getNotifyUrl());
        request.setOutTradeNo(IdUtil.fastSimpleUUID());
        // 调用下单方法，得到应答
        PrepayResponse response = service.prepay(request);
        // 使用微信扫描 code_url 对应的二维码，即可体验Native支付
        System.out.println(response.getCodeUrl());
        return Result.ok();
    }


    @PostMapping("/request")
    @Operation(summary = "微信支付小程序下单")
    public Result<MiniappPrepayVo> request(@RequestBody RequestPay pay){
        MiniappPrepayVo vo= payService.request(pay);
        return Result.ok(vo);
    }

    @PostMapping("/callback")
    @Operation(summary = "支付回调通知")
    public ResponseEntity<Object> callBack(@RequestBody String requestBody){
        return payService.callBack(requestBody);
    }

    @GetMapping("/query")
    @Operation(summary = "主动查询支付状态")
    public Result<Void> query(@RequestParam String orderNo){
         payService.query(orderNo);
         return Result.ok();
    }
}
